/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mirac
 * Date: 2025-09-08
 * Time: 15:50
 */
public class HashBuck<K,V> {
    static class Node<K,V> {
        public K key;
        public V val;
        public Node<K,V> next;

        public Node(K key, V val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node<K,V>[] arr = (Node<K,V>[])new Node[10];
    public int userSize;
    public static final double  DEFAULT_LOAD_FACTOR = 0.75f;

    public void put(K key,V val) {
        int hashCode = key.hashCode();
        int index = hashCode % arr.length;
        Node<K,V> cur = arr[index];
        while (cur != null) {
            if (cur.key.equals(key)) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        Node<K,V> node = new Node<>(key,val);
        node.next = arr[index];
        arr[index] = node;
        userSize++;
        if (doLoadFactor() >= DEFAULT_LOAD_FACTOR) {
            reSize();
        }
    }

    private void reSize() {
        Node<K,V>[] newArr = (Node<K,V>[])new Node[2*arr.length];
        for (int i = 0; i < arr.length; i++) {
            Node<K,V> cur = arr[i];
            while (cur != null) {
                Node<K,V> curN = cur.next;
                int newIndex = cur.key.hashCode() % newArr.length;
                cur.next = newArr[newIndex];
                newArr[newIndex] = cur;
                cur = curN;
            }
        }
        arr = newArr;
    }

    private double doLoadFactor() {
        return userSize*1.0/arr.length;
    }

    public V getVal(K key) {
        Node<K,V> cur = arr[key.hashCode() % arr.length];
        while (cur != null) {
            if (cur.key.equals(key)) {
                return cur.val;
            }
            cur = cur.next;
        }
        //找不到返回null
        return null;
    }
}
